package com.inossem.warehousestorage_inossem.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.inossem.utils.base.Utils;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.test.TestActivity;
import com.inossem.warehousestorage_inossem.adapter.FunctionListAdapter;
import com.inossem.warehousestorage_inossem.application.WarehouseStorageApplication;
import com.inossem.warehousestorage_inossem.bean.base.CheckVersionBean;
import com.inossem.warehousestorage_inossem.bean.base.GetFunctionListBean;
import com.inossem.warehousestorage_inossem.dialog.UpgradeVersionDialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.model.FunctionItem;
import com.inossem.warehousestorage_inossem.request.base.CheckVersionRequest;
import com.inossem.warehousestorage_inossem.request.base.MainRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;
import com.zhy.android.percent.support.PercentRelativeLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.inossem.warehousestorage_inossem.R.id.headerTitle;

public class MainActivity extends BaseActivity {

    private static final int DELAY_EXIT_APP_TIME = 2000;

    private TextView title, userName;

    private PercentRelativeLayout leftTitleLayout;

    private GridView functionList;

    private View userNameView;

    private boolean backKeyPressed = false;


    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        initView(MainActivity.this);
        initData(MainActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(headerTitle);
        functionList = (GridView) activity.findViewById(R.id.functionList);
        leftTitleLayout = (PercentRelativeLayout) activity.findViewById(R.id.leftTitleLayout);
        userNameView = LayoutInflater.from(activity).inflate(R.layout.include_user_name, null);
        userName = (TextView) userNameView.findViewById(R.id.userName);
        //初始化左上角登录用户名称
        leftTitleLayout.addView(userNameView);
    }

    private void initData(Activity activity) {
        title.setText(activity.getResources().getString(R.string.activity_main_title));
        title.setOnClickListener(new View.OnClickListener() {
            long beginTime = 0, endTime = 0;

            int count = 1;

            @Override
            public void onClick(View v) {
                endTime = System.currentTimeMillis();
                if ((endTime - beginTime) < 500) {
                    count++;
                } else {
                    count = 1;
                }
                beginTime = endTime;
                if (count == 10) {
                    Intent intent = new Intent(activity, TestActivity.class);
                    startActivity(intent);
                }
            }
        });
        userName.setText(SPUtils.getName(activity));
//        userName.setOnClickListener(new NoDoubleClickListener() {
//            @Override
//            public void onNoDoubleClick(View v) {
//                Utils.middleToast(activity, "versionName:" + Utils.getVersion_name(activity) + "\nversionCode:" + Utils.getVersion_code(activity));
//                Test401Request.request(activity, new GsonBeanListener() {
//                    @Override
//                    public void onSuccess(Object bean) {
//                    }
//                });
//            }
//        });
        //初始化右上角退出登录图片按钮
        ActivityUtils.initRightFunction(activity, getRightFunction(activity), new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                //登出
                clear(activity);
                WarehouseStorageApplication.getInstance().removeAllActivity();
                startActivity(new Intent(activity, LoginActivity.class));
            }
        });
        checkVersion(activity);
    }

    private void clear(Context context) {
        SPUtils.clearSystem(context);
        SPUtils.clearWarehouseStorage(context);
    }

    private View getRightFunction(Context context) {
        View rightFunctionView = LayoutInflater.from(context).inflate(R.layout.include_right_function, null);
        ImageView rightFunction = (ImageView) rightFunctionView.findViewById(R.id.rightFunction);
        rightFunction.setImageResource(R.drawable.ico_logout);
        return rightFunctionView;
    }

    private void checkVersion(Activity activity) {
        CheckVersionRequest.request(activity, new GsonBeanListener<CheckVersionBean>() {
            @Override
            public void onSuccess(CheckVersionBean bean) {
                CheckVersionBean.BodyBean.VersionBean version = bean.getBody().getVersion();
                if (version.getVersion_code() == null) {
                    getData(activity);
                } else {
                    Dialog dialog = UpgradeVersionDialogUtils.getUpgradeVersionDialog(activity, version.getSize(), version.getVersion_name(), version.getVersion_description(), version.getUrl(), version.getMd5(), null);
                    dialog.setCancelable(false);
                    dialog.show();
                }
            }

            @Override
            public void onDefaultError(Context context, String code, String msg) {
                super.onDefaultError(context, code, msg);
                List<FunctionItem> list = ActivityUtils.getCommonFunctionItemList(activity);
                FunctionListAdapter functionListAdapter = new FunctionListAdapter(activity, list);
                functionList.setAdapter(functionListAdapter);
            }

        });
    }

    @Override
    public void onBackPressed() {
        if (!backKeyPressed) {
            Utils.middleToast(MainActivity.this, MainActivity.this.getResources().getString(R.string.activity_main_exit_prompt));
            backKeyPressed = true;
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    backKeyPressed = false;
                }
            }, DELAY_EXIT_APP_TIME);
        } else {
            WarehouseStorageApplication.getInstance().removeAllActivity();
            finish();
            System.exit(0);
        }
    }

    private void getData(Activity activity) {
        MainRequest.request(activity, new GsonBeanListener<GetFunctionListBean>() {
            @Override
            public void onSuccess(GetFunctionListBean bean) {
                List<GetFunctionListBean.BodyBean.FunctionListBean> showFunctionList = bean.getBody().getFunction_list();
                List<FunctionItem> functionItemList = getShowFunctionList(ActivityUtils.getFunctionItemList(activity), showFunctionList);
                functionItemList.addAll(ActivityUtils.getCommonFunctionItemList(activity));
                FunctionListAdapter functionListAdapter = new FunctionListAdapter(activity, functionItemList);
                functionList.setAdapter(functionListAdapter);
            }
        });
    }

    private List<FunctionItem> getShowFunctionList(List<FunctionItem> allFunctionList, List<GetFunctionListBean.BodyBean.FunctionListBean> showFunctionList) {
        List<FunctionItem> result = new ArrayList<>();
        for (int i = 0; i < showFunctionList.size(); i++) {
            GetFunctionListBean.BodyBean.FunctionListBean showFunction = showFunctionList.get(i);
            for (int j = 0; j < allFunctionList.size(); j++) {
                FunctionItem allFunction = allFunctionList.get(j);
                if (showFunction.getId().equals(allFunction.getId())) {
                    allFunction.setFunctionName(showFunction.getName());
                    result.add(allFunction);
                    break;
                }
            }
        }
        return result;
    }

    @Override
    protected void onActivityResultImpl(int requestCode, int resultCode, Intent data) {
        if (requestCode == ActivityUtils.REQUEST_CODE_SYSTEM_SETTING && resultCode == Activity.RESULT_OK) {
            //无法访问到服务器，进入系统设置修改ip和端口后返回主页面重新请求获取功能列表
            getData(MainActivity.this);
        }
    }
}
